import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)
// 处理路由跳转到当前页报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err)
}

const routes = [
  {
    path: '/',
    redirect: '/dashboard/welcome'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login')
  },
  {
    path: '/dashboard',
    component: () => import('@/views/Home'),
    children: [
      {
        path: '/dashboard/welcome',
        component: () => import('@/components/Homemain'),
      },
      {
        path: '/dashboard/user/index',
        component: () => import('@/views/user/Index')
      },
      {
        path: '/dashboard/user/add',
        component: () => import('@/views/user/Add')
      },
      {
        path: '/dashboard/user/mod',
        component: () => import('@/views/user/Edit')
      },
      {
        path: '/dashboard/film/index',  // 电影列表
        component: () => import('@/views/film/Index')
      },
      {
        path: '/dashboard/film/add',
        component: () => import('@/views/film/Dialog')
      },
      {
        path: '/dashboard/cinema/index',  // 影院列表
        component: () => import('@/views/cinema/Index')
      },
      {
        path: '/dashboard/cinema/add',
        component: () => import('@/views/cinema/Add')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//路由前置守卫
router.beforeEach((to, from, next) => {
  // 判断是否要登录
  if (to.path === '/login') {
    next()
  } else {
    // 判断是否登录
    if (store.state.token) {
      next()
    } else {
      router.push('/login')
    }
  }
})

// 权限防翻墙 - 当前登录的这个用户，具有哪些权限，规定只能访问auth_path
// 如果访问本身不具备的权限对应的页面 - 会到首页
router.afterEach((to, from) => {
  let index = store.state.auth.findIndex(item => item === to.path)
  if (index < 0) {
    router.push('/')
  }
})

export default router
